package com.itheima.boot.controller;

import com.itheima.boot.domain.Book;
import com.itheima.boot.domain.R;
import com.itheima.boot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private  BookService bookService;

    @PostMapping
    public R save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        if (flag){
            return R.success();
        }else {
            return R.error();
        }
    }

    @PutMapping
    public R update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        if (flag){
            return R.success();
        }else {
            return R.error();
        }
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        if (flag){
            return R.success();
        }else {
            return R.error();
        }
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable Integer id) {

        Book book = bookService.getById(id);

        if (book!=null){
            return R.success(book);
        }else {
            return R.error("数据查询失败，请重试!");
        }
    }

    @GetMapping
    public R getAll(String bookName,Integer status) {
        List<Book> bookList = bookService.getAll(bookName,status);
        if (bookList.size()!=0){
            return R.success(bookList);
        }else {
            return R.error("数据查询失败，请重试!");
        }
    }

}
